/*
 * @lc app=leetcode.cn id=1574 lang=cpp
 *
 * [1574] 删除最短的子数组使剩余数组有序
 */

// @lc code=start
class Solution
{
public:
    int findLengthOfShortestSubarray(vector<int> &arr)
    {
        int n = arr.size(), p = n - 1;
        while (p > 0 && arr[p - 1] <= arr[p])
            p--;
        if (p == 0)
            return 0;

        int ans = p;
        for (int i = 0; i < n; i++)
        {
            if (i && arr[i - 1] > arr[i])
                break;

            while (p <= i || (p < n && arr[p] < arr[i]))
                p++;
            ans = min(ans, p - i - 1);
        }

        return ans;
    }
};
// @lc code=end
